package cn.qiyu5522.tk_ems.controller.admin;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import cn.hutool.core.util.ObjectUtil;
import cn.qiyu5522.tk_ems.entity.Classroom;
import cn.qiyu5522.tk_ems.entity.Department;
import cn.qiyu5522.tk_ems.entity.Major;
import cn.qiyu5522.tk_ems.entity.User;
import cn.qiyu5522.tk_ems.result.R;
import cn.qiyu5522.tk_ems.service.ClassroomService;
import cn.qiyu5522.tk_ems.service.DepartmentService;
import cn.qiyu5522.tk_ems.service.MajorService;
import cn.qiyu5522.tk_ems.service.UserService;
import cn.qiyu5522.tk_ems.utils.RedisKey;
import cn.qiyu5522.tk_ems.utils.RedisUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.constraints.NotNull;
import java.util.List;

/**
 * @BelongsProject: tk_ems
 * @BelongsPackage: cn.qiyu5522.tk_ems.controller.admin
 * @Author: TangQi
 * @CreateTime: 2023-02-01  10:09
 * @Description: TODO
 * @Version: 1.0
 */
@Api(tags = "系统登录模块")
@RestController
@RequestMapping("/admin/login")
@Slf4j
@Validated
public class LoginController {

    @Resource
    private UserService userService;
    @Resource
    private RedisUtil redisUtil;
    @Resource
    private DepartmentService departmentService;
    @Resource
    private MajorService majorService;
    @Resource
    private ClassroomService classroomService;

//    @WebLog(description = "用户登录")
    @ApiOperation("用户登录")
    @ApiImplicitParams(
            {
                    @ApiImplicitParam(name = "username", value = "账号", required = true, defaultValue = "admin", dataTypeClass=String.class ),
                    @ApiImplicitParam(name = "password", value = "密码", required = true, defaultValue = "111111", dataTypeClass=String.class)
            }
    )
    @PostMapping("doLogin")
    public R doLogin(@NotNull(message = "账号不能为空")
                             String username,
                     @NotNull(message = "密码不能为空")
                             String password) {
        // 查询用户表
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(User::getUsername, username).eq(User::getPassword, password);
        User user = userService.getOne(lambdaQueryWrapper);
        // 将院系、专业、班级的编号与名称集合存入 redis，有效期一天，
        this.initDepAndMajorAndClassroomForIdAndName();
        if (ObjectUtil.isNotEmpty(user)) {
            if(user.getState().equals(1)){
                return R.error().message("用户已停用");
            }
            // 第1步，先登录上
            StpUtil.login(user.getId()+"-"+user.getName());
            // 第2步，获取 Token  相关参数
            SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
            // 第3步，返回给前端
            return R.ok().message("登录成功").data("tokenInfo", tokenInfo);
        }
        return R.error().message("登录失败");
    }

    public void initDepAndMajorAndClassroomForIdAndName(){
        // 将院系编号与名称集合存入redis
        QueryWrapper<Department> departmentQueryWrapper = new QueryWrapper<>();
        departmentQueryWrapper.select("id","name");
        List<Department> departments = departmentService.list(departmentQueryWrapper);
        redisUtil.set(RedisKey.DEPARTMENT_ID_AND_NAME,departments,RedisKey.EXPIRE_ONE_DAY);
        // 将专业编号与名称集合存入redis
        QueryWrapper<Major> majorQueryWrapper = new QueryWrapper<>();
        majorQueryWrapper.select("id","name","department_id");
        List<Major> majors = majorService.list(majorQueryWrapper);
        redisUtil.set(RedisKey.MAJOR_ID_AND_NAME,majors,RedisKey.EXPIRE_ONE_DAY);
        // 将班级编号与名称集合存入redis
        QueryWrapper<Classroom> classroomQueryWrapper = new QueryWrapper<>();
        classroomQueryWrapper.select("id","name","major_id","department_id");
        List<Classroom> classrooms = classroomService.list(classroomQueryWrapper);
        redisUtil.set(RedisKey.CLASSROOM_ID_AND_NAME,classrooms,RedisKey.EXPIRE_ONE_DAY);
    }

    // 查询登录状态，
    @GetMapping("isLogin")
    public String isLogin() {
        return "当前会话是否登录：" + StpUtil.isLogin();
    }


    // 查询 Token 信息
    @GetMapping("tokenInfo")
    public SaResult tokenInfo() {
        return SaResult.data(StpUtil.getTokenInfo());
    }


    // 测试注销
    @PostMapping("logout")
    public SaResult logout() {
        StpUtil.logout();
        return SaResult.ok("退出成功");
    }

}
